import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      //模型
      models: {
        //模型

        collectionPoint: {
          ...typeClassName["collectionPoint"],
        },
        equipment: {
          ...typeClassName["equipment"],
        },
      },
      equipmentTreeData: [],
      parentId: "",
      ids: "",
      dataSet: {
        //数据集
        treeData: [],
        treeCurrentData: [],
        currentData: {},
        equipmentTreePoint: {},
        pointTableData: [],
        formData: {
          equipmentTypeName: "",
          equipmentTypeCode: "",
        },
        tableData: [],
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      console.log(comp, "comp");
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      this.init();
      this.getReturnTrue();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {
      // this.getEquipTypeOptions();
    },
    loadPage(pageNavigation, filter) {
      let newFilter = {
        ...filter,
        className: this.models.collectionPoint.className,
        type: this.models.collectionPoint.type,
      };
      let hierFilter = this._$setFilteStr(newFilter, false);
      hierFilter = hierFilter + `&& id in (${this.ids})`;
      this._$queryByPage(
        this.models["collectionPoint"].clzs,
        pageNavigation,
        hierFilter,
        "",
        "updateTime",
        false
      ).then((res) => {
        this.dataSet.tableData =
          this.models["collectionPoint"].clzs.valueRecords;
      });
    },
    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      if (this.dataSet.treeCurrentData.length > 0) {
        // this.vms.createView.resetFields();
        this._modalShow("createModal");
        this.dataSet.formData["equipmentTypeName"] =
          this.dataSet.treeCurrentData[0].data.sf_name;
        this.dataSet.formData["equipmentTypeCode"] =
          this.dataSet.treeCurrentData[0].data.id;
        this.dataSet.formData.status = "是"
      } else {
        this.$Message.info("请选择设备");
      }
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
      this.dataSet.formData["equipmentTypeName"] =
        this.dataSet.treeCurrentData[0].data.sf_name;
      this.dataSet.formData["equipmentTypeCode"] =
        this.dataSet.treeCurrentData[0].data.id;
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      console.log(row);
      this._modalShow("editModal");
      this.dataSet.currentData = row;
      this.dataSet.formData = row.values;
      this.dataSet.formData["equipmentTypeName"] =
        this.dataSet.treeCurrentData[0].data.sf_name;
      this.dataSet.formData["equipmentTypeCode"] =
        this.dataSet.treeCurrentData[0].data.id;
    },
    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models.collectionPoint.clzs, [
            String(row.id),
          ])
          .then((res) => {
            this.queryEquipPointByEquId(this.dataSet.treeCurrentData[0].data);
          });
      });
    },
    handleDeleteMultiple(selection) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.id));
        _this
          ._$deleteByIds(_this.models.collectionPoint.clzs, ids)
          .then((res) => {
            _this.vms.mainTable.navigation.page.pageNumber = 1;
            _this.loadPage(_this.vms.mainTable.navigation, {
              equipmentTypeCode: this.dataSet.formData.values.equipmentTypeCode,
            });
          });
      });
    },
    // 新增确认
    createModalOk(btn) {
      this.vms.createView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          let formData = this.$modelObject.getTpl(
            this.models.collectionPoint.modelType
          );
          formData.className = this.models.collectionPoint.className;
          formData.type = this.models.collectionPoint.type;
          formData.name = +new Date();
          formData.containerId =
            this.dataSet.equipmentTreePoint.hier.containerId;
          formData.values = this.dataSet.formData;
          this.$api.inspection.addCollectionPoint(formData).then((flag) => {
            this.queryEquipPointByEquId(this.dataSet.treeCurrentData[0].data);

            this._modalClose("createModal");
            this._resetForm("createView");
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
      btn.loading = false;
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          this.dataSet.currentData.values = {
            ...this.dataSet.formData,
          };
          this.models.collectionPoint.clz.setRecord(this.dataSet.currentData);
          this.models.collectionPoint.clz.updateById().then((flag) => {
            if (flag) {
              this.queryEquipPointByEquId(this.dataSet.treeCurrentData[0].data);
              this._modalClose("editModal");
            } 
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
      btn.loading = false;
    },
    treeSelect(item, data) {
      console.log(item, data);
      this.dataSet.treeCurrentData = data;
      this.dataSet.tableData = [];
      if (data.length == 0) {
        return;
      }
      this.queryEquipPointByEquId(item);
      // this.loadPage(this.vms.mainTable.navigation.page,{equipmentTypeCode:item.id})
    },
    queryEquipPointByEquId(item) {
      this.$api.inspection.queryEquipPointByEquId(item).then((res) => {
        this.dataSet.equipmentTreePoint = res;
        this.parentId = this._$getHierItemField(res.hier, "采集点", "nodeId");
        if (!this.parentId) {
          return;
        }
        let arr = this.dataSet.equipmentTreePoint.hier.content.filter(
          (item) => item.parentId == this.parentId
        ); // 进入页面点击设备存储所有的选项
        if (arr.length == 0) {
          this.dataSet.tableData = []
          this.vms.mainTable.navigation.page.total = 0
          return
        }
        this.ids = arr.map((item) => item.link.linkId).join(",");
        this.loadPage(this.vms.mainTable.navigation.page, {});
        //   if (this.dataSet.pointTableData.length > 0) {
        //     this.dataSet.tableData = this.dataSet.pointTableData.map((item) => {
        //       return {
        //         ...item,
        //         values: {
        //           ...item.values,
        //         },
        //         ...item.values,
        //       };
        //     });
        //   } else {
        //     this.dataSet.pointTableData = []
        //   }
      });
    },

    getReturnTrue() {
      Promise.all([this.getEquipTypeOptions()]).then((res) => {
        console.log(res);
        // this.result = res[0];
        this.vms.createView.beforePageInit();
        this.vms.editView.beforePageInit();
        this.vms.detailView.beforePageInit();
      });
    },
    getEquipTypeOptions() {
      let data = {
        className: this.models.equipment.className,
        type: this.models.equipment.type,
      };
      this.dataSet.treeData = [];
      this._$query(this.models.equipment.clzs, data).then((res) => {
        this.models.equipment.clzs.records.forEach((d) => {
          this.dataSet.treeData.push({
            id: d.id,
            parentId: "root",
            name: d.values.sf_name,
            sf_name: d.values.sf_name,
            sf_code: d.values.sf_code,
          });
        });
      });
    },
  },
};
